const word =document.getElementById('word');
const text =document.getElementById('text');
const scoreEl =document.getElementById('score');
const timeEl =document.getElementById('time');
const endgameEl =document.getElementById('end-game-container');
const settingsBtn =document.getElementById('settings-btn');
const settings =document.getElementById('settings');
const settingsForm =document.getElementById('settings-form');
const difficultySelect =document.getElementById('difficulty');

const words = [
    'const',
    'let',
    'input',
    'image',
    'form',
    'style',
    'display',
    'container',
    'element',
    'class',
    'document',
    'background',
    'transition',
    'transform',
    'translate',
    'border',
    'radius',
    'margin',
    'padding',
    'select'
    ];

    //初始化单词
    let randomWord;

    //初始化分数
    let score = 0;

    //初始化时间
    let time = 10;

    //设置难度值为LS中的值或者中等难度
    let difficulty = localStorage.getItem('difficulty') !==null ? localStorage.getItem('difficulty') : 'medium';


    //将难度值输出到下拉选项中
    difficultySelect.value = difficulty;

    //开始时聚焦到输入框
    text.focus();

    //从时间开始倒数
    const timeInterval = setInterval(updateTime, 1000);

    //从数组中获取随机单词
    function getRandomWord(){
        return words[Math.floor(Math.random() * words.length)];
    }

    //输出单词到 DOM
    function addWordToDOM(){
        randomWord = getRandomWord();
        word.innerHTML = randomWord;
    }

    //更新分数
    function updateScore(){
        score++;
        scoreEl.innerHTML = score;
    }

    //更新时间
    function updateTime(){
        time--;
        timeEl.innerHTML = time + 's';

        if(time === 0){
            clearInterval(timeInterval);
            //结束游戏
            gameOver();
        }
    }

    //结束游戏，展示结束游戏界面
    function gameOver(){
        endgameEl.innerHTML =`
        <h1>时间结束了</h1>
        <p>你的最终分数是${score}</p>
        <button onClick="location.reload()">再来一次</button>
        `;

        endgameEl.style.display = 'flex';
    }

    addWordToDOM();

    //事件监听器

    //输入文字
    text.addEventListener('input', function(e){
        const insertedText = e.target.value;
        
        if(insertedText === randomWord){
            addWordToDOM();
            updateScore();

            //清除输入框
            e.target.value = '';

            if(difficulty === 'hard'){
                time += 2;
            }else if (difficulty === 'medium'){
                time += 3;
            } else{
                time += 5;
            }
            
            updateTime();
        }
    })

    //设置按钮点击
    settingsBtn.addEventListener('click', function(){
        settings.classList.toggle('hide');
    })

    //设置下拉选项
    settingsForm.addEventListener('change',function(e){
        difficulty = e.target.value;
        localStorage.setItem('difficulty', difficulty);
    })